import request from "../../utils/request";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    cartCount: 0,
    appArray: [],
    ruzhuArray: [],
    ziyingArray: [],
    haohuaArray: [],
    gaojiArray: [],
    biaozhunArray: [],
    jiagouTitle: [],
    SRC:
      "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/0.png",
    poentSrc:
      "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/category-image/poent.png",
    result: ["a", "b"],
    activeNames: ["1"],
    show: false,
    allShow: true,
    showPro: true,
    allShowPro: false,
    showProMax: true,
    allShowProMax: false,
    showMultiMerchant: true,
    allShowMultiMerchant: false,
    showAPP: true,
    allShowAPP: false,
    typeSize1: null,
    typeSize2: null,
    typeList1: {},
    typeList2: {},
    addgouShow: false,
    dataList: [],
    standardArry1: [],
    nameList: [],
    displayStatusMap: {
      25: false,
      27: false,
      28: false,
      29: false,
      30: false,
      31: false,
    },
    boxStyle:
      "display: flex;width: 100%;height: 75px;color: #d3d2d1;font-size: 28rpx;justify-content: center;align-items: center;border-bottom: 1rpx solid #818181;border-left: 1rpx solid #818181;box-sizing: border-box;padding:25rpx;",
    checked: false,
    notSameSenior: [],
    notSameStandard: [],
    notSameLuxurious: [],
    notSameMultiple: [],
    notSameRuzhu: [],
    notSameAPPList: [],
    versionsList: [],
    biaozhunArray: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getpakege();
    this.getSelectlist();
  },
  async getpakege() {
    const AllList = wx.getStorageSync("alllist");
    if (AllList) {
      this.setData({
        dataList: AllList,
        standard: AllList.filter((item) => item.id === 25),
        senior: AllList.filter((item) => item.id === 27),
        luxurious: AllList.filter((item) => item.id === 28),
        multiple: AllList.filter((item) => item.id === 29),
        ruzhu: AllList.filter((item) => item.id === 30),
        APPList: AllList.filter((item) => item.id === 31),
      });
      const typeList = AllList.filter((item) => item.id === 25);
      const list = typeList[0].functions;
      this.getTypeList(list);
      this.standardArray();
      this.seniorArray();
      this.luxuriousArray();
      this.multipleArray();
      this.ruzhuArray()
      this.APPListArray();
    } else {
      const res = await request({
        url: app.globalData.baseURL + "/app-api/package/packages/page",
        method: "GET",
        data: {
          pageNo: 1,
          pageSize: 10,
          categoryId: 10,
        },
      });
      const List = res.data.list.reverse();
      const AllList = List.map((item) => {
        if (item.price && typeof item.price === "number") {
          item.price = (item.price / 100).toFixed(2);
        }
        return item;
      });
      wx.setStorageSync("alllist", AllList);
      this.setData({
        dataList: AllList,
        standard: AllList.filter((item) => item.id === 25),
        senior: AllList.filter((item) => item.id === 27),
        luxurious: AllList.filter((item) => item.id === 28),
        multiple: AllList.filter((item) => item.id === 29),
        ruzhu: AllList.filter((item) => item.id === 30),
        APPList: AllList.filter((item) => item.id === 31),
      });
      const typeList = AllList.filter((item) => item.id === 25);
      const list = typeList[0].functions;
      this.getTypeList(list);
      this.standardArray();
      this.seniorArray();
      this.luxuriousArray();
      this.multipleArray();
      this.ruzhuArray()
      this.APPListArray();
    }

    const data = this.data.standard[0].functions;
    let groupedArray = data.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 id，则创建一个新的数组
      if (!accumulator[current.packageCategoryName]) {
        accumulator[current.packageCategoryName] = [];
      }
      // 将当前元素添加到对应 id 的数组中
      accumulator[current.packageCategoryName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.values(groupedArray);
  },
  getTypeList(list) {
    let nameCount = {};
    list.forEach((item) => {
      if (nameCount[item.functionTypeName]) {
        nameCount[item.functionTypeName] += 1;
      } else {
        nameCount[item.functionTypeName] = 1;
      }
    });
    // 一定要在循环外部初始化数组
    let namesArray = [];
    for (let name in nameCount) {
      namesArray.push({ title: name, frequency: nameCount[name] });
    }
    this.setData({
      nameList: namesArray,
    });
  },
  async getSelectlist() {
    const res = await request({
      url:
        app.globalData.baseURL +
        `/app-api/package/package-function/selectlist?packageId=${25}`,
      method: "GET",
    });
    let list = res.data;
    const priceList = list.map((item) => {
      item.functionPrice = (item.functionPrice / 100).toFixed(2);
      return item;
    });
    this.setData({
      jiagouTitle: priceList,
    });
  },
  async addCartBadge(e) {
    let item = e.currentTarget.dataset.item;
    this.updateCartBadge(item);
    const res = await request({
      url: app.globalData.baseURL + "/app-api/package/cart/create",
      method: "POST",
      data: {
        mainItem: true,
        itemId: item.id,
        years: 1,
      },
    });
  },
  getList() {
    const cartCount = wx.getStorageSync("count");
    this.setData({
      cartCount: cartCount,
    });
  },
  async updateCartBadge(item) {
    const app = getApp();
    const useID = wx.getStorageSync("userId");
    const res = await request({
      url:
        app.globalData.baseURL +
        `/app-api/package/cart/page?pageNo=${1}&pageSize=${50}`,
      method: "GET",
      userId: useID,
    });
    const list = res.data.list;
    this.setData({
      cartList: list,
    });
    const cartList = this.data.cartList;
    let isExist = false; // 标记是否找到相同的商品

    // 如果购物车列表不为空，检查商品是否已存在
    if (cartList.length > 0) {
      for (let i = 0; i < cartList.length; i++) {
        if (cartList[i].itemId === item.id) {
          isExist = true;
          break;
        }
      }
    }

    if (!isExist) {
      // 如果商品不存在，添加到购物车列表
      cartList.push(item);
      let cart = wx.getStorageSync("count");
      cart += 1; // 增加购物车商品数量
      wx.showToast({
        title: "加入配置清单成功",
        icon: "none",
      });

      // 存储到本地存储
      wx.setStorageSync("count", cart);
      this.setData({
        cartCount: cart,
      });
      wx.setStorageSync("cartList", cartList);
    } else {
      // 如果商品已存在，显示错误提示
      wx.showToast({
        title: "商品已存在",
        icon: "none",
      });
    }
  },
  addShow() {
    this.setData({
      addgouShow: !this.data.addgouShow,
    });
  },
  goback() {
    wx.navigateBack({
      delta: 1,
    });
  },
  biaozhun(e) {
    let num = e.currentTarget.dataset.item.id;
    this.pushData(num);
    if (this.data.typeSize1 === null || this.data.typeSize2 === null) {
      this.setData({
        checked: false,
      });
      this.getpakege();
    }
  },
  gaoji(e) {
    let num = e.currentTarget.dataset.param;
    this.pushData(num);
  },
  haohua(e) {
    let num = e.currentTarget.dataset.param;
    this.pushData(num);
  },
  ziying(e) {
    let num = e.currentTarget.dataset.param;
    this.pushData(num);
  },
  app(e) {
    let num = e.currentTarget.dataset.param;
    this.pushData(num);
  },
  onChange(event) {
    this.setData({
      result: event.detail,
    });
  },
  pushData(num) {
    let that = this;
    if (that.data.typeSize1 === null && that.data.typeSize2 !== num) {
      that.setData({
        typeSize1: num,
      });
      this.setData({
        [`displayStatusMap.${num}`]: !this.data.displayStatusMap[num],
      });
      this.add();
    } else if (that.data.typeSize2 === null && that.data.typeSize1 !== num) {
      that.setData({
        typeSize2: num,
      });
      this.setData({
        [`displayStatusMap.${num}`]: !this.data.displayStatusMap[num],
      });
      this.add();
    } else if (that.data.typeSize1 === num && that.data.typeSize2 === num) {
      that.setData({
        typeSize1: null,
        typeList2: {},
        typeList1: {},
        typeSize2: null,
      });
      this.setData({
        [`displayStatusMap.${num}`]: !this.data.displayStatusMap[num],
      });
      this.detail();
    } else if (that.data.typeSize1 === num) {
      that.setData({
        typeSize1: null,
        typeList1: {},
      });
      this.setData({
        [`displayStatusMap.${num}`]: !this.data.displayStatusMap[num],
      });
      this.detail();
    } else if (that.data.typeSize2 === num) {
      that.setData({
        typeSize2: null,
        typeList2: {},
      });
      this.setData({
        [`displayStatusMap.${num}`]: !this.data.displayStatusMap[num],
      });
      this.detail();
    } else if (that.data.typeSize1 !== num && that.data.typeSize2 !== num) {
      wx.showToast({
        title: "最多只能添加两项做对比",
        icon: "none",
      });
    }
  },
  onChange1(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  onChangeSwitch({ detail }) {
    if (this.data.typeSize1 === null || this.data.typeSize2 === null) {
      wx.showToast({
        title: "至少两个套餐才可以展示不同",
        icon: "none",
      });
    } else {
      this.setData({ checked: detail });
      this.comparisonFunction();
    }
    if (detail === false) {
      this.getpakege();
    }
  },
  comparisonFunction() {
    const list = wx.getStorageSync("alllist");
    let notSameList1 = list.filter((item) => item.id === this.data.typeSize1);
    let notSameList2 = list.filter((item) => item.id === this.data.typeSize2);
    let notSameStandard = [];
    let notSameSenior = [];
    for (let i = 0; i < notSameList1[0].functions.length; i++) {
      if (
        notSameList1[0].functions[i].choosed !==
          notSameList2[0].functions[i].choosed ||
        notSameList1[0].functions[i].remark !==
          notSameList2[0].functions[i].remark
      ) {
        notSameStandard.push(notSameList1[0].functions[i]);
        notSameSenior.push(notSameList2[0].functions[i]);
      }
    }
    if (this.data.typeSize1 === 25) {
      this.setData({
        notSameStandard: notSameStandard,
        versionsList: notSameStandard,
      });
      this.getTypeList(notSameStandard);
    }
    if (this.data.typeSize2 === 25) {
      this.setData({
        notSameStandard: notSameSenior,
        versionsList: notSameSenior,
      });
      this.getTypeList(notSameSenior);
    }
    if (this.data.typeSize1 === 27) {
      this.setData({
        notSameSenior: notSameStandard,
        versionsList: notSameStandard,
      });
      this.getTypeList(notSameStandard);
    }
    if (this.data.typeSize2 === 27) {
      this.setData({
        notSameSenior: notSameSenior,
        versionsList: notSameSenior,
      });
      this.getTypeList(notSameSenior);
    }
    if (this.data.typeSize1 === 28) {
      this.setData({
        notSameLuxurious: notSameStandard,
        versionsList: notSameStandard,
      });
      this.getTypeList(notSameStandard);
    }
    if (this.data.typeSize2 === 28) {
      this.setData({
        notSameLuxurious: notSameSenior,
        versionsList: notSameSenior,
      });
      this.getTypeList(notSameSenior);
    }
    if (this.data.typeSize1 === 29) {
      this.setData({
        notSameMultiple: notSameStandard,
        versionsList: notSameStandard,
      });
      this.getTypeList(notSameStandard);
    }
    if (this.data.typeSize2 === 29) {
      this.setData({
        notSameMultiple: notSameSenior,
        versionsList: notSameSenior,
      });
      this.getTypeList(notSameSenior);
    }
    if (this.data.typeSize1 === 30) {
      this.setData({
        notSameRuzhu: notSameStandard,
        versionsList: notSameStandard,
      });
      this.getTypeList(notSameStandard);
    }
    if (this.data.typeSize2 === 30) {
      this.setData({
        notSameRuzhu: notSameSenior,
        versionsList: notSameSenior,
      });
      this.getTypeList(notSameSenior);
    }
    if (this.data.typeSize1 === 31) {
      this.setData({
        notSameAPPList: notSameStandard,
        versionsList: notSameStandard,
      });
      this.getTypeList(notSameStandard);
    }
    if (this.data.typeSize2 === 31) {
      this.setData({
        notSameAPPList: notSameSenior,
        versionsList: notSameSenior,
      });
      this.getTypeList(notSameSenior);
    }
  },
  openShow(event) {
    // 更新 versionList 数组的 show 属性
    let versionList = this.data.dataList.map((item) => {
      const index = event.currentTarget.dataset.index;
      return {
        ...item,
        show: item.id === index ? true : false,
      };
    });

    // 更新页面数据
    this.setData({
      dataList: versionList,
      SRC:
        "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/1.png",
    });
  },
  openShowPro() {
    this.setData({
      SRC:
        "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/0.png",
      show: true,
      allShow: false,
      showPro: false,
      allShowPro: true,
      showProMax: true,
      allShowProMax: false,
      showMultiMerchant: true,
      allShowMultiMerchant: false,
      showAPP: true,
      allShowAPP: false,
    });
  },
  openShowProMax() {
    this.setData({
      show: true,
      allShow: false,
      showPro: true,
      allShowPro: false,
      showProMax: false,
      allShowProMax: true,
      showMultiMerchant: true,
      allShowMultiMerchant: false,
      showAPP: true,
      allShowAPP: false,
    });
  },
  openMultiMerchant() {
    this.setData({
      show: true,
      allShow: false,
      showPro: true,
      allShowPro: false,
      showProMax: true,
      allShowProMax: false,
      showMultiMerchant: false,
      allShowMultiMerchant: true,
      showAPP: true,
      allShowAPP: false,
    });
  },
  openAPP() {
    this.setData({
      show: true,
      allShow: false,
      showPro: true,
      allShowPro: false,
      showProMax: true,
      allShowProMax: false,
      showMultiMerchant: true,
      allShowMultiMerchant: false,
      showAPP: false,
      allShowAPP: true,
    });
  },
  add() {
    wx.showToast({
      title: "添加对比成功",
      icon: "success",
      duration: 2000,
    });
  },
  detail() {
    wx.showToast({
      title: "取消对比成功",
      icon: "success",
      duration: 2000,
    });
  },
  getOrderList() {
    const count = wx.getStorageSync("count");
    this.setData({
      cartCount: count,
    });
  },
  addComparison(event) {
    console.log("event", event);
  },
  standardArray() {
    const list = this.data.standard[0].functions;
    let groupedItems = list.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 functionTypeName
      if (!accumulator[current.functionTypeName]) {
        accumulator[current.functionTypeName] = [];
      }
      // 将当前元素添加到对应 functionTypeName 的数组中
      accumulator[current.functionTypeName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.keys(groupedItems).map((key) => ({
      name: key,
      items: groupedItems[key],
    }));
    let newArray = resultArray.reduce((accumulator, current) => {
      // 使用 map 方法遍历当前项的 item 数组，并将其元素添加到累加器数组中
      accumulator.push(...current.items);
      return accumulator;
    }, []); // 初始化累加器为一个空数组
    this.setData({
      biaozhunArray: newArray,
    });
  },
  seniorArray() {
    const list = this.data.senior[0].functions;
    let groupedItems = list.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 functionTypeName
      if (!accumulator[current.functionTypeName]) {
        accumulator[current.functionTypeName] = [];
      }
      // 将当前元素添加到对应 functionTypeName 的数组中
      accumulator[current.functionTypeName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.keys(groupedItems).map((key) => ({
      name: key,
      items: groupedItems[key],
    }));
    let newArray = resultArray.reduce((accumulator, current) => {
      // 使用 map 方法遍历当前项的 item 数组，并将其元素添加到累加器数组中
      accumulator.push(...current.items);
      return accumulator;
    }, []); // 初始化累加器为一个空数组
    this.setData({
      gaojiArray: newArray,
    });
  },
  luxuriousArray() {
    const list = this.data.luxurious[0].functions;
    let groupedItems = list.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 functionTypeName
      if (!accumulator[current.functionTypeName]) {
        accumulator[current.functionTypeName] = [];
      }
      // 将当前元素添加到对应 functionTypeName 的数组中
      accumulator[current.functionTypeName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.keys(groupedItems).map((key) => ({
      name: key,
      items: groupedItems[key],
    }));
    let newArray = resultArray.reduce((accumulator, current) => {
      // 使用 map 方法遍历当前项的 item 数组，并将其元素添加到累加器数组中
      accumulator.push(...current.items);
      return accumulator;
    }, []); // 初始化累加器为一个空数组
    this.setData({
      haohuaArray: newArray,
    });
  },
  multipleArray() {
    const list = this.data.multiple[0].functions;
    let groupedItems = list.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 functionTypeName
      if (!accumulator[current.functionTypeName]) {
        accumulator[current.functionTypeName] = [];
      }
      // 将当前元素添加到对应 functionTypeName 的数组中
      accumulator[current.functionTypeName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.keys(groupedItems).map((key) => ({
      name: key,
      items: groupedItems[key],
    }));
    let newArray = resultArray.reduce((accumulator, current) => {
      // 使用 map 方法遍历当前项的 item 数组，并将其元素添加到累加器数组中
      accumulator.push(...current.items);
      return accumulator;
    }, []); // 初始化累加器为一个空数组
    this.setData({
      ziyingArray: newArray,
    });
  },
  ruzhuArray() {
    const list = this.data.ruzhu[0].functions;
    let groupedItems = list.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 functionTypeName
      if (!accumulator[current.functionTypeName]) {
        accumulator[current.functionTypeName] = [];
      }
      // 将当前元素添加到对应 functionTypeName 的数组中
      accumulator[current.functionTypeName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.keys(groupedItems).map((key) => ({
      name: key,
      items: groupedItems[key],
    }));
    let newArray = resultArray.reduce((accumulator, current) => {
      // 使用 map 方法遍历当前项的 item 数组，并将其元素添加到累加器数组中
      accumulator.push(...current.items);
      return accumulator;
    }, []); // 初始化累加器为一个空数组
    this.setData({
      ruzhuArray: newArray,
    });
  },
  APPListArray() {
    const list = this.data.APPList[0].functions;
    let groupedItems = list.reduce((accumulator, current) => {
      // 如果 accumulator 中还没有当前 functionTypeName
      if (!accumulator[current.functionTypeName]) {
        accumulator[current.functionTypeName] = [];
      }
      // 将当前元素添加到对应 functionTypeName 的数组中
      accumulator[current.functionTypeName].push(current);
      return accumulator;
    }, {});

    // 将分组后的对象转换为数组
    let resultArray = Object.keys(groupedItems).map((key) => ({
      name: key,
      items: groupedItems[key],
    }));
    let newArray = resultArray.reduce((accumulator, current) => {
      // 使用 map 方法遍历当前项的 item 数组，并将其元素添加到累加器数组中
      accumulator.push(...current.items);
      return accumulator;
    }, []); // 初始化累加器为一个空数组
    this.setData({
      appArray: newArray,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "嘉之勤官网小程序",
      path: "/pages/index/index",
      imageUrl:
        "https://youyougo2.oss-cn-chengdu.aliyuncs.com/0201506f6fc0f4145e34159c2e2ac66b94b96450dd29e5a19d177edc5dad8023.png",
    };
  },
});
